import { FC, ReactElement, useEffect, useRef } from "react";
import styled, { keyframes } from "styled-components";

interface IProps {
  content?: string;
}

const WaveText: FC<IProps> = ({ content = "HELLO" }): ReactElement => {
  const contRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const cont = contRef.current;
    const { offsetWidth } = document.body;
    if (!cont || offsetWidth > 750) return;
    const { offsetTop, offsetHeight } = cont;
    const overCont = offsetHeight + offsetTop;
    const scrollBack = () => {
      const already = cont.getAttribute("already");
      if (window.scrollY > overCont) {
        if (!already) {
          cont.setAttribute("already", "true");
          cont.style["transform"] = "translateX(-50%)";
        }
      } else {
        if (already) {
          cont.style["transform"] = "";
          cont.setAttribute("already", "");
        }
      }
    };
    document.addEventListener("scroll", scrollBack);
    // 其他页面不需要监听滚动事件
    return () => {
      document.removeEventListener("scroll", scrollBack);
    };
  }, []);

  return (
    <Container ref={contRef} data-wave-text>
      <Hello content={content}>{content}</Hello>
      <TempText>{content}</TempText>
    </Container>
  );
};

export default WaveText;

const Container = styled.div`
  height: 3rem;
  overflow: hidden;
  position: sticky;
  position: -webkit-sticky;
  top: 0.5rem;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 5;
  font-size: 2.5rem;
  transition: transform 0.3s linear;
`;

const animate = keyframes`
    0%{
      background-position-x: 0;
    }
    
    50%{
      background-position-y: 2.5rem;
    }
    
    100%{
      background-position-x: -4rem;
      background-position-y: -2px;
    }
`;

const Hello = styled.span<{ content: string }>`
  background: url("/wave.svg") no-repeat;
  background-size: 15rem;
  animation: ${animate} 6s ease-out infinite running;
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  position: relative;
  font-weight: bold;
  ::before {
    content: ${props => props.content};
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    -webkit-text-fill-color: transparent;
    -webkit-text-stroke: 1px transparent;
  }
`;

const colorTrans = keyframes`
  0%{
    color:transparent;
  }
  12%{
    color:#51f;
  }
  50%{
    color:#11d6f9;
  }
  75%{
    color:#faa;
  }
  90%{
    color:#faa;
  }
  100%{
    color:transparent;
  }
`;

const TempText = styled.span`
  font-weight: bold;
  position: absolute;
  z-index: -1;
  /* animation: ${colorTrans} 10s linear infinite running; */
`;
